package com.netease.controller;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.netease.jichu.Product;
import com.netease.service.ProductService;

@Controller
public class ContentController {
	@Autowired
	private ProductService ps;
	@RequestMapping(value="/edit")
	//内容编辑
	public String edit(
			Product product){
//		ps.add(product);
		return "edit";
	}
//	@RequestMapping("/edit/{id}")
//	public ModelAndView editUI(@PathVariable(value = "id") int id,
//			HttpServletRequest request){
//			
//				return null;
//		
//	}
	@RequestMapping("/editSubmit")
	public String update(Product product,HttpServletRequest request){
		product.setDetail(request.getParameter("detail"));
		ps.update(product);
		return "editSubmit";
		
	}
	@RequestMapping(value="/public")
	//内容发布
	public String pub(Product product){
		return"public";
	}
	@RequestMapping(value="/api/upload")
	public void upload(MultipartFile productImg, HttpServletRequest request,
			Product product){
		//上传图片
		String path ="/web-work/src/main/webapp/upload";
		String fileName = productImg.getOriginalFilename();
		File targetFile = new File(path, fileName);
		product.setImage(fileName);; // 设置数据库中图片保存的路径
		ps.add(product);
		// 如果文件上传路径不存在就创建
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			// 保存文件
			productImg.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping(value="/publicSubmit",method=RequestMethod.POST)
	//内容提交
	public String addProduct(Product product){
		ps.add(product);
		return"publicSubmit";
	}
	@RequestMapping(value="/api/delete",method=RequestMethod.POST)
	public String delete(int id,Model model){
		ps.deleteProduct(id);
		model.addAttribute("code",200);
		model.addAttribute("result",true);
		return "model";
	}
}
